package ruifeng.zcj.happymahjony.wxapi;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import com.google.gson.Gson;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.tencent.mm.sdk.constants.ConstantsAPI;
import com.tencent.mm.sdk.modelbase.BaseReq;
import com.tencent.mm.sdk.modelbase.BaseResp;
import com.tencent.mm.sdk.modelbase.BaseResp.ErrCode;
import com.tencent.mm.sdk.modelmsg.SendAuth;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import cn.sharesdk.wechat.utils.WXAppExtendObject;
import cn.sharesdk.wechat.utils.WXMediaMessage;
import cn.sharesdk.wechat.utils.WechatHandlerActivity;
import ruifeng.zcj.happymahjony.AbJsonUtil;
import ruifeng.zcj.happymahjony.FragmentArgs;
import ruifeng.zcj.happymahjony.Result;
import ruifeng.zcj.happymahjony.ToActivityUtil;
import ruifeng.zcj.happymahjony.TokenBean;
import ruifeng.zcj.happymahjony.activity.sub.MainCordovaActivity;
import ruifeng.zcj.happymahjony.constant.KeyConstant;
import ruifeng.zcj.happymahjony.util.AppUtil;
import ruifeng.zcj.happymahjony.util.CacheApi;
import ruifeng.zcj.happymahjony.util.SPUtils;
import ruifeng.zcj.happymahjony.util.SpUtil;

public class WXEntryActivity extends WechatHandlerActivity implements IWXAPIEventHandler {

    private IWXAPI api;

    private TokenBean tokenBean;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        api = WXAPIFactory.createWXAPI(this, KeyConstant.APP_ID_WX);// wxaaeac85f01714b29
        api.handleIntent(getIntent(), this);
    }

    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        api.handleIntent(getIntent(), this);
    }

    public void onReq(BaseReq arg0) {

    }

    public void onResp(BaseResp resp) {
        if (resp instanceof SendAuth.Resp) {
            SendAuth.Resp newResp = (SendAuth.Resp) resp;
            switch (newResp.errCode) {
                case ErrCode.ERR_OK:// 用户同意
                    // 获取微信传回的code
                    Toast.makeText(getApplicationContext(), "请稍后", Toast.LENGTH_SHORT).show();
                    String code = newResp.code;
                    getToken(code);
                    Log.e("399", code);


                    break;
                case ErrCode.ERR_AUTH_DENIED:// 用户拒绝授权

                    break;
                case ErrCode.ERR_USER_CANCEL:// 用户取消

                    break;
                default:
                    break;
            }

        }


        switch (resp.errCode) {
            case BaseResp.ErrCode.ERR_OK: {// 分享成功
                switch (resp.getType()) {//
                    case ConstantsAPI.COMMAND_SENDMESSAGE_TO_WX:
                        //分享回调,处理分享成功后的逻辑
                        Toast.makeText(getApplicationContext(), "分享成功", Toast.LENGTH_SHORT).show();
                        finish();
                        break;
                    default:
                        break;
                }
            }
            break;
            case BaseResp.ErrCode.ERR_USER_CANCEL:
                //  Toast.makeText(getApplicationContext(), "分享取消", Toast.LENGTH_SHORT).show();
//                finish();
                break;
            case BaseResp.ErrCode.ERR_AUTH_DENIED:
                // Toast.makeText(getApplicationContext(), "权限拒绝", Toast.LENGTH_SHORT).show();
//                finish();
                break;
            default:
                break;
        }
    }

    /**
     * 获取token
     *
     * @param code
     */
    private void getToken(String code) {
        //Toast.makeText(getApplicationContext(), "成功", 1).show();
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token";
        HttpUtils httpUtils = new HttpUtils();
        RequestParams params = new RequestParams();
        params.addBodyParameter("appid", "wx59be6d3005b2973e");
        params.addBodyParameter("secret", "817ad90d2992e84ba33426e10fe54589");
        params.addBodyParameter("code", code);
        params.addBodyParameter("grant_type", "authorization_code");
        httpUtils.send(HttpMethod.POST, url, params, new RequestCallBack<String>() {

            @Override
            public void onFailure(HttpException arg0, String arg1) {
                Log.e("399", "失败");

            }

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                String result = responseInfo.result;
                Gson gson = new Gson();
                tokenBean = gson.fromJson(result, TokenBean.class);
                Log.e("399", tokenBean.toString());
                getUserInfo(tokenBean);
            }
        });
    }

    private void getUserInfo(TokenBean tokenBean) {
        String url = "https://api.weixin.qq.com/sns/userinfo";
        HttpUtils httpUtils = new HttpUtils();
        RequestParams params = new RequestParams();
        params.addBodyParameter("access_token", tokenBean.access_token);
        params.addBodyParameter("openid", tokenBean.openid);
        httpUtils.send(HttpMethod.POST, url, params, new RequestCallBack<String>() {

            @Override
            public void onFailure(HttpException arg0, String arg1) {
                Log.e("399", "失败");
            }

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
//                CacheApi.cacheStringUserMessage(responseInfo.result, "login");
                SPUtils.put(WXEntryActivity.this, SPUtils.USER_INFO, responseInfo.result);
                sendhttp(responseInfo.result);

			/*	Intent intent = new Intent();
                intent.putExtra("result", responseInfo.result);
				setResult(1, intent);
				Toast.makeText(getApplicationContext(), ""+responseInfo.result, 1).show();
				finish();
				overridePendingTransition(0, 0);*/
            }
        });
    }


    private void sendhttp(String tokenBean) {
        // http://mj.lcc.so/wxlogin
        String url = "http://mj.lcc.so/wxlogin";
        HttpUtils httpUtils = new HttpUtils();
        RequestParams params = new RequestParams();
        params.addBodyParameter("user_message",   AppUtil.getUserMessage(tokenBean,this));
        httpUtils.send(HttpMethod.POST, url, params, new RequestCallBack<String>() {

            @Override
            public void onFailure(HttpException arg0, String arg1) {
                Log.e("399", "失败");
                Toast.makeText(getApplicationContext(), "" + arg1, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                //  Toast.makeText(getApplicationContext(), "" + responseInfo.result, Toast.LENGTH_SHORT).show();

                Result result = (Result) AbJsonUtil.fromJson(responseInfo.result, Result.class);


                if (result.getStatus() == 1) {
                    FragmentArgs args = new FragmentArgs();
                    args.add("result", result);


                    ToActivityUtil.toNextActivityAndFinish(WXEntryActivity.this, MainCordovaActivity.class, "key", args);

                } else {
                    Toast.makeText(getApplicationContext(), "登录失败,请稍后再试", Toast.LENGTH_SHORT).show();

                }
                return;
              /*  Intent intent = new Intent();
                intent.putExtra("result", responseInfo.result);
                startActivity(intent);
                setResult(1, intent);
                overridePendingTransition(0, 0);*/

                // overridePendingTransition(0, 0);
                //finish();
                /*Log.e("399", responseInfo.result);
                Intent intent = new Intent();
				intent.putExtra("result", responseInfo.result);
				startActivity(intent);
				setResult(1, intent);
//				Toast.makeText(getApplicationContext(), ""+responseInfo.result, 1).show();
				finish();
				overridePendingTransition(0, 0);*/
            }
        });
    }


    /**
     * 处理微信发出的向第三方应用请求app message
     * <p/>
     * 在微信客户端中的聊天页面有“添加工具”，可以将本应用的图标添加到其中
     * 此后点击图标，下面的代码会被执行。Demo仅仅只是打开自己而已，但你可
     * 做点其他的事情，包括根本不打开任何页面
     */
    public void onGetMessageFromWXReq(WXMediaMessage msg) {
        if (msg != null) {
            Intent iLaunchMyself = getPackageManager().getLaunchIntentForPackage(getPackageName());
            startActivity(iLaunchMyself);
        }
    }

    /**
     * 处理微信向第三方应用发起的消息
     * <p/>
     * 此处用来接收从微信发送过来的消息，比方说本demo在wechatpage里面分享
     * 应用时可以不分享应用文件，而分享一段应用的自定义信息。接受方的微信
     * 客户端会通过这个方法，将这个信息发送回接收方手机上的本demo中，当作
     * 回调。
     * <p/>
     * 本Demo只是将信息展示出来，但你可做点其他的事情，而不仅仅只是Toast
     */
    public void onShowMessageFromWXReq(WXMediaMessage msg) {
        if (msg != null && msg.mediaObject != null
                && (msg.mediaObject instanceof WXAppExtendObject)) {
            WXAppExtendObject obj = (WXAppExtendObject) msg.mediaObject;
            Toast.makeText(this, obj.extInfo, Toast.LENGTH_SHORT).show();
        }
    }
}
